package com.fzy.springsecurity.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fzy
 * @version 1.0
 * 创建时间：2024-10-05 18:15
 */

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> json = new HashMap<>();
        json.put("code", 401);
        json.put("msg", "登录失败");
        json.put("data", exception.getMessage());
        response.getWriter().println(new ObjectMapper().writeValueAsString(json));
    }
}
